#include "util.hpp"

#include <cstdio>
#include <functional>
#include <vector>

#define INIT(v)                  \
    do                           \
    {                            \
        v.push_back(printlog);   \
        v.push_back(download);   \
        v.push_back(executeSql); \
    } while (0)
#define EXEC_OTHER(cbs)            \
    do                             \
    {                              \
        for (auto const &cb : cbs) \
        {                          \
            cb();                  \
        }                          \
    } while (0)

using func_t = std::function<void()>;

int main()
{
    std::vector<func_t> cbs;
    INIT(cbs);
    for (;;)
    {
        SetNonBlock(0);
        printf(">>> ");
        fflush(stdout);
        char buffer[1024];
        ssize_t s = read(0, buffer, sizeof(buffer) - 1); // 从输入文件描述符读
        if (s > 0)
        {
            buffer[s - 1] = 0; // 去掉输入的enter
            std::cout << "echo# " << buffer << std::endl;
        }
        else if (s == 0)
        {
            std::cout << "read end" << std::endl;
            break;
        }
        else
        {
            // 1. 如果非阻塞，不输入，底层没有数据时，不算错误，只不过以错误的形式返回了
            // 2. 如何区分是，错了还是底层没有数据？错误码
            if (errno == EAGAIN) // EWOULDBACK
            {
                std::cout << "没错，只是底层没有数据" << std::endl;
                EXEC_OTHER(cbs);
            }
            else if (errno == EINTR) // 系统中断
            {
                continue;
            }
            else
            {
                std::cout << "s: " << "errno " << errno << " " << strerror(errno) << std::endl;
                break;
            }
        }
        sleep(1);
    }
    return 0;
}